﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Collections.Concurrent;
using Newtonsoft.Json;

namespace SocketClient
{
    class SocketClient
    {
        private static Socket socket;
        static ReceiveDataUnpack messageHandle= new ReceiveDataUnpack();
        static Data data=new Data();
        static ConcurrentQueue<String> concurrentQueue = new ConcurrentQueue<String>();
        static void Main(string[] args)
        {
            int port = 2333;
            String ip = "127.0.0.1";
            IPAddress address = IPAddress.Parse(ip);
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint endPoint = new IPEndPoint(address, port);
            socket.Connect(endPoint);
            
            Thread send = new Thread(Send);
            send.Start();
             Thread receive = new Thread(Receive);
             receive.Start();
             
            String name = Console.ReadLine();
            data.name=name;
            while (true)
            {
                String content = Console.ReadLine();
                data.content = content;
                string jsonData = JsonConvert.SerializeObject(data);
                concurrentQueue.Enqueue(jsonData);
            }

        }


        private static void Send()
        {
            String message;
            while (true)
            {
                Thread.Sleep(5);
                if(!concurrentQueue.IsEmpty)
                {
                    concurrentQueue.TryDequeue(out message);
                    socket.Send (TCPpackage.wrap(message));
                }
            }
        }
        
        private static void Receive()
        {
            //String message;
            while (true)
            {
                int datanum =socket.Receive(messageHandle.DataBuffer);
                messageHandle.ReadMessage(datanum);
                if (messageHandle.isRead)
                {
                    Data data = JsonConvert.DeserializeObject<Data>(messageHandle.ReceiveStr);
                    Console.WriteLine("{0}发送消息:{1}",data.name,data.content);
                }
            }
        }
    }
}
